package com.example.myapplication11;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService2 extends Service {
    boolean flag = false;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private Handler handler = new Handler();
    private Runnable r = new Runnable() {
        @Override
        public void run() {
            if(flag){
                //使用工具类的getForegroundActivityName方法获取栈顶的应用包名
                String foregroundActivityName = ForegroundAppUtil.getForegroundActivityName(getApplicationContext());
                if(foregroundActivityName.indexOf("login")==-1){
                    Log.i("Service","-----start other activity-----");
                }else {
                    Log.i("Service","-----start Login activity-----");
                    Log.i("Service","-----"+foregroundActivityName+"-----");

                }
                Toast.makeText(getApplicationContext(), foregroundActivityName, Toast.LENGTH_SHORT).show();
                //使用PostDelayed方法，三秒后调用此Runnable对象
                handler.postDelayed(r, 3000);
            }
        }
    };
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        flag = true;
        handler.postDelayed(r, 2000);
        Log.d("MyService", "onStartCommand opened");
        return START_STICKY;
    }
    public void onDestroy() {
        flag = false;
        super.onDestroy();
        Log.d("MyService", "onDestroy executed");
    }
}